const userService = require('../service/user.service')
const authService = require('../service/auth.service')
const errorTypes = require('../constans/error-types')
const md5password = require('../utils/password-handle')
const jwt = require('jsonwebtoken')
const { PUBLIC_KEY } = require('../app/config')

// 验证账号密码中间件
const verifyAuthLogin = async (ctx, next) => {
    // 1.获取用户名和密码
    const { userName, password } = ctx.request.body
    // 2.判断用户名或者密码不能空
    if (!userName || !password) {
        const error = new Error(errorTypes.NAME_OR_PASSWORD_IS_REQUIRED);
        return ctx.app.emit('error', error, ctx);
    }
    // 3.判断这次登录的用户名是存在的
    const result = await userService.getUserByName(userName);
    const user = result[0]
    if (!result.length) {
        const error = new Error(errorTypes.USER_DOES_NOT_EXISTS);
        return ctx.app.emit('error', error, ctx);
    }
    // 4.判断用户的密码正确
    if (md5password(password) !== user.password) {
        const error = new Error(errorTypes.PASSWORD_IS_INCORRENT);
        return ctx.app.emit('error', error, ctx);
    }
    ctx.user = user

    await next()
}

//测试token授权
const verifyAuth = async (ctx, next) => {
    console.log("验证token授权的middleware~");
    // 获取token
    const authorization = ctx.headers.authorization
    // 未传token
    if (!authorization) {
        const error = new Error(errorTypes.UNAUTHORIZATION);
        return ctx.app.emit('error', error, ctx);
    }
    const token = authorization.replace('Bearer ', '');
    try {
        const result = jwt.verify(token, PUBLIC_KEY, {
            algorithms: ['RS256']
        })
        ctx.user = result
        await next()
    } catch (err) {
        // console.log(err)
        const error = new Error(errorTypes.UNAUTHORIZATION);
        ctx.app.emit('error', error, ctx);
    }

}

// 验证用户是否具备操作权限
const verifyPermission = async (ctx, next) => {
    console.log("验证操作权限的middleware~");
        const parpams = ctx.params
        const resultKey = Object.keys(parpams)[0]
        const tableName = resultKey.replace('Id', "")
        const tableId = parpams[resultKey]
        const { id } = ctx.user
    
    try {
        const isPermission = await authService.checkResource(tableName, tableId, id)
        if (!isPermission) throw new Error();
        await next()
    } catch (err) {
        const error = new Error(errorTypes.UNPERMISSION);
        return ctx.app.emit('error', error, ctx);
    }

}

module.exports = {
    verifyAuthLogin,
    verifyAuth,
    verifyPermission
}